﻿

using Mrc.Data;
using System;
using System.Collections.Generic;
using System.Text;
using Mrc.Entity;
using Chloe;
using System.Linq.Expressions;

namespace Mrc.Application
{
    public interface ISysPermissionService : IServiceBase<SysPermission>, IMrcService
    {
        List<SysPermission> GetList(PermissionType? type = null);
        List<SysPermission> GetPermissionMenus();
        void isHadPermissionCode(string permissionCode, string id, out string msg);
    }
    public class SysPermissionService : ServiceBase<SysPermission>, ISysPermissionService
    {
        public SysPermissionService(IDbContext dbContext, IServiceProvider services) : base(dbContext, services)
        {

        }
        public List<SysPermission> GetList(PermissionType? type = null)
        {
            var q = this.DbContext.Query<SysPermission>();
            q = q.WhereIfNotNull(type, a => a.Type == (int)type);
            return q.OrderBy(t => t.SortCode).ToList();
        }
        public List<SysPermission> GetPermissionMenus()
        {
            var q = this.DbContext.Query<SysPermission>();
            q = q.Where(a => a.Type == (int)PermissionType.节点组 || a.Type == (int)PermissionType.公共菜单 || a.Type == (int)PermissionType.权限菜单);
            return q.ToList();
        }
        public void isHadPermissionCode(string permissionCode, string id,out string msg)
        {
            msg = "";
            if (permissionCode.IsNotNullOrEmpty())
            {
                bool exists = this.DbContext.Query<SysPermission>().WhereIfNotNull(id, a => a.Id != id).Any(a => a.Code == permissionCode);
                if (exists)
                    msg = ($"权限码 {permissionCode} 已存在，无法重复添加");
            }
        }
    }
}
